'use strict';

const { doCrypto } = require('../utils/cryp');
const { ErrorModel, SuccessModel } = require('../utils/resultModel');
const { loginFailInfo, deleteUserFailInfo } = require('../utils/ErrorModel');
const { formatUser } = require('../utils/formatUser');
const Service = require('egg').Service;

class UserService extends Service {

  // 创建用户
  async createUser({ userName, password, gender = 1, nickName }) {
    const result = this.app.model.User.create({
      userName,
      password: doCrypto(password),
      gender,
      nickName: nickName ? nickName : nickName = userName,
    });
    
    return result;
  }

  // 获取用户信息
  async getUserInfo(userName, password) {
    const whereOption = { userName };

    if (password) {
      Object.assign(whereOption, { password: doCrypto(password) });
    }

    // 查询
    const result = await this.app.model.User.findOne({
      attributes: ['id', 'userName', 'nickName', 'city', 'gender', 'avatar'],
      where: whereOption,
    });

    return formatUser(result);
  }

  // 登录
  async doLogin({ userName, password }) {
    if (!password) {
      return new ErrorModel(loginFailInfo);
    }
    // 通过用户名和密码查找用户信息
    const result = await this.getUserInfo(userName, password);

    if (result) {
      // 保存到session中userInfo
      if (!this.ctx.session.userInfo) {
        // 判断session是否存在，session中是否存在userInfo
        // 不存在，则设置
        this.ctx.session.userInfo = result;
      }
      return new SuccessModel(result);
    }
    return new ErrorModel(loginFailInfo);
  }

  // 删除当前用户
  async deleteCurrentUser(userName) {
    // destroy
    const result = await this.app.model.User.destroy({
      where: {
        userName,
      },
    });

    if (result > 0) {
      // 删除成功
      return new SuccessModel();
    }
    // 删除失败
    return new ErrorModel(deleteUserFailInfo);
  }

  // 更新用户
  /**
   * 更新用户 jsDoc
   * @param {object} param0 更新后的值 newNickName, newCity, newAvatar, newPassword
   * @param {object} param1 查询条件 userName, password
   */
  async updateUser({ newNickName, newCity, newAvatar, newPassword }, { userName, password }) {
    const updateData = {};

    if (newPassword) {
      updateData.password = doCrypto(newPassword);
    }
    if (newNickName) {
      updateData.nickName = newNickName;
    }
    if (newCity) {
      updateData.city = newCity;
    }
    if (newAvatar) {
      updateData.avatar = newAvatar;
    }
    const whereData = {
      userName,
    };
    if (password) {
      whereData.password = doCrypto(password);
    }
    const result = await this.app.model.User.update(updateData, {
      where: whereData,
    });
    return result > 0; // true/false
    // console.log(whereData, updateData);
    // if (result > 0) {
    //   // assign 对象拼接，如果有相同的属性名，后面的属性值会覆盖前面的值
    //   Object.assign(this.ctx.session.userInfo, updateData);
    //   return new SuccessModel();
    // }
    // return new ErrorModel(changeInfoFailInfo);
  }



}


module.exports = UserService;
